package com.it.reggie.exception;

import com.it.reggie.common.Result;
import com.sun.org.apache.bcel.internal.generic.IF_ACMPEQ;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * @author:cyh
 * @data:2022/12/14 18:42
 */
//指定拦截那些类型的控制器;
@ControllerAdvice
//将方法的返回值 R 对象转换为json格式的数据, 响应给页面;
@ResponseBody
@Slf4j
public class GlobalException {
    /**
     * 异常处理方法
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg=split[2]+ "已存在";
            return Result.filed(msg);
        }
        return Result.filed("未知错误");
    }
}
